﻿/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MyPhotoIndex.Interfaces;
using MyPhotoIndex.Controls;
using MyPhotoIndex.Utilities;
using System.Diagnostics;

namespace MyPhotoIndex.Plugins.WebHost
{
    public partial class SettingsForm : FormTemplate
    {
        private bool m_closing = false;
        private Stats m_stats;
        private HttpHost m_httpHost;

        public SettingsForm(IApplicationContext applicationContext, ref HttpHost host)
        {
            InitializeComponent();

            m_httpHost = host;
            m_stats = host.Stats;

            useAuthCheckBox.Checked = WebHostPluginSettings.Default.UseAuthentication;
            userNameTextBox.Text = WebHostPluginSettings.Default.UserName;
            passwordTextBox.Text = WebHostPluginSettings.Default.Password;

            enableUpnpPortMappingCheckBox.Checked = WebHostPluginSettings.Default.OpenNATPortForwarding;
            addWinFirewallExceptionCheckBox.Checked = WebHostPluginSettings.Default.OpenFirewallPort;

            UpdateForm();

            startButton.Click += new EventHandler(startButton_Click);
            useAuthCheckBox.CheckedChanged += new EventHandler(useAuthCheckBox_CheckedChanged);

            timer1.Interval = 1000;
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Enabled = true;

            m_httpHost.IsRunningChanged += new EventHandler(m_httpHost_IsRunningChanged);
            testButton.Click += new EventHandler(testButton_Click);
        }

        void testButton_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("http://127.0.0.1:" + m_httpHost.Port.ToString());
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }

        void m_httpHost_IsRunningChanged(object sender, EventArgs e)
        {
            UpdateForm();

            if (m_httpHost.IsRunning == true)
            {
                hostsListBox.Items.AddRange(m_httpHost.ServerAddress.ToArray());
            }

            testButton.Enabled = m_httpHost.IsRunning;

        }

        void useAuthCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            UpdateForm();
        }

        private void UpdateForm()
        {
            httpPortTextBox.Text = WebHostPluginSettings.Default.Port.ToString();
            httpPortTextBox.Enabled = (m_httpHost.IsRunning == false);

            startButton.Text = (m_httpHost.IsRunning == false) ? "Start" : "Stop";
            startButton.Enabled = true;

            hostsListBox.Items.Clear();
            testButton.Enabled = false;

            bool enabled = (m_httpHost.IsRunning == false);
            useAuthCheckBox.Enabled = enabled;
            userNameTextBox.Enabled = enabled;
            passwordTextBox.Enabled = enabled;
            enableUpnpPortMappingCheckBox.Enabled = enabled;
            addWinFirewallExceptionCheckBox.Enabled = enabled;

            bool visible = (useAuthCheckBox.Checked == true);
            userNameLabel.Visible = visible;
            passwordLabel.Visible = visible;
            userNameTextBox.Visible = visible;
            passwordTextBox.Visible = visible;

            testButton.Enabled = m_httpHost.IsRunning;
        }

        void startButton_Click(object sender, EventArgs e)
        {
            startButton.Enabled = false;

            UpdateSettings();
            UpdateForm();

            bool beforeState = m_httpHost.IsRunning;

            if (m_httpHost.IsRunning == true)
            {
                m_httpHost.Stop();
            }
            else
            {
                m_httpHost.Port = WebHostPluginSettings.Default.Port;
                m_httpHost.UseAuthentication = WebHostPluginSettings.Default.UseAuthentication;

                m_httpHost.Start();
            }

            if (beforeState != m_httpHost.IsRunning)
            {
                UpdateSettings(); // save running state to user settings.
            }
        }

        private void UpdateSettings()
        {
            WebHostPluginSettings.Default.Port = Convert.ToInt32(httpPortTextBox.Text);
            WebHostPluginSettings.Default.UseWebInterface = m_httpHost.IsRunning;
            WebHostPluginSettings.Default.UseAuthentication = useAuthCheckBox.Checked;
            WebHostPluginSettings.Default.UserName = userNameTextBox.Text.Trim();
            WebHostPluginSettings.Default.Password = passwordTextBox.Text.Trim();
            WebHostPluginSettings.Default.OpenNATPortForwarding = enableUpnpPortMappingCheckBox.Checked;
            WebHostPluginSettings.Default.OpenFirewallPort = addWinFirewallExceptionCheckBox.Checked;
            WebHostPluginSettings.Default.Save();
        }

        protected override void OkButton_Click(object sender, EventArgs e)
        {
            UpdateSettings();

            base.OkButton_Click(sender, e);
        }

        public void CloseForm()
        {
            m_closing = true;
            this.Close();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            this.Visible = false;

            if (m_closing == false)
            {
                e.Cancel = true;
            }
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = m_stats.RequestsPerSecond.ToString();

            DrawGraph(m_stats.RequestsPerOneMinute, pictureBox1);
        }

        private int m_graphWidth = 130;
        private int m_markerPos = 130;
        private void DrawGraph(List<int> list, PictureBox pictureBox)
        {
            if (pictureBox.Image != null)
            {
                pictureBox.Image.Dispose();
            }

            Image graphImage = new Bitmap(m_graphWidth, pictureBox1.Height);

            using (Graphics g = Graphics.FromImage(graphImage))
            {
                g.Clear(Color.White);

                g.DrawLine(Pens.Black, new Point(5, 0), new Point(5, graphImage.Height - 5));
                g.DrawLine(Pens.Black, new Point(5, graphImage.Height - 5), new Point(graphImage.Width, graphImage.Height - 5));

                for (int j = 5; j < (graphImage.Height - 5); j += 5)
                {
                    g.DrawLine(Pens.Black, new Point(3, j), new Point(5, j));
                }

                if (m_markerPos < 6)
                {
                    m_markerPos = m_graphWidth;
                }
                g.DrawLine(Pens.Red, new Point(m_markerPos, graphImage.Height - 6), new Point(m_markerPos, 0));
                m_markerPos -= 2;


                List<int> listCopy = new List<int>(list);
                listCopy.Reverse();

                int x = graphImage.Width - 5;
                foreach (int value in listCopy)
                {
                    g.DrawLine(Pens.BlueViolet, new Point(x, graphImage.Height - 5), new Point(x, graphImage.Height - value - 5));
                    x -= 2;
                }
            }

            pictureBox1.Image = graphImage;
        }
    }
}
